// 云函数入口文件
const cloud = require('wx-server-sdk')

// 初始化云开发
cloud.init({
  env: 'liucheng-2gmqvcgs50e86304' // 使用指定的云环境
});

// 云函数入口函数
exports.main = async (event, context) => {
  const db = cloud.database()
  const { accountnumber, password, role } = event

  let collectionName

  // 根据角色选择相应的数据库表
  if (role === 'Boss') {
    collectionName = 'Boss'
  } else if (role === 'Manufacturer') {
    collectionName = 'ManufacturerReg'
  } else if (role === 'Users') {
    collectionName = 'User'
  } else {
    return {
      success: false,
      message: '角色无效'
    }
  }

  try {
    console.log(`Logging in user with accountnumber: ${accountnumber}, role: ${role}`)
    // 查询对应表中的 accountnumber
    const userRes = await db.collection(collectionName).where({
      accountnumber: accountnumber
    }).get()

    console.log("查询数据库获取的信息",userRes)

    // 检查是否找到匹配的用户
    if (userRes.data.length === 0) {
      console.warn(`Account number ${accountnumber} not found in ${collectionName} table`)
      return {
        success: false,
        message: '账号不存在'
      }
    }

    // 检查密码是否正确
    if (userRes.data[0].password !== password) {
      console.warn(`Incorrect password for account number ${accountnumber} in ${collectionName} table`)
      return {
        success: false,
        message: '密码错误'
      }
    }

    console.log(`User found and password verified in ${collectionName} table`)
    return {
      success: true,
      message: '登录成功',
      data: userRes.data[0] // 返回用户信息
    }
  } catch (error) {
    console.error('Error occurred:', error.message)
    return {
      success: false,
      message: '错误: ' + error.message
    }
  }
}
